package ECTranslator

import (
	"ZxDict/pkg/ECTranslator/wordnet"
	"ZxDict/pkg/util"
	"sort"
)

var wordNetLib *wordnet.WordNet
var englishWordMap map[string]bool

type EETranslateResult struct {
	Word        string
	MinDistance int
	Synset      map[string][]*wordnet.Synset
}

func (t EETranslateResult) String() string {
	return t.Word
}

/*
Translator
英译英翻译入口
输入：待翻译的英文单词
返回：英文翻译结果，若没有该单词则返回最短编辑距离小于3的所有词汇
*/
func Translator(s string) []EETranslateResult {
	var ret []EETranslateResult
	synset := wordNetLib.Search(s)

	// turn to fuzzy search if results is empty
	if len(synset["a"])+len(synset["n"])+len(synset["r"])+len(synset["v"]) != 0 {
		ret = append(ret, EETranslateResult{
			Word:        s,
			MinDistance: 0,
			Synset:      synset,
		})
	} else {
		for k := range englishWordMap {
			dis := util.MinDistance(k, s)
			if dis <= 3 {
				ret = append(ret, EETranslateResult{
					Word:        k,
					MinDistance: dis,
					Synset:      wordNetLib.Search(s),
				})
			}

			sort.Slice(ret, func(i, j int) bool {
				if ret[i].MinDistance != ret[j].MinDistance {
					return ret[i].MinDistance < ret[j].MinDistance
				} else {
					return ret[i].Word < ret[j].Word
				}
			})
		}
	}

	return ret
}

func init() {
	wordNetLib, _ = wordnet.Parse("dict")
	englishWordMap = make(map[string]bool)
	for _, synset := range wordNetLib.Synset {
		for _, word := range synset.Word {
			englishWordMap[word] = true
		}
	}
}
